package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    DishService dishService;
    @Autowired
    DishFlavorService dishFlavorService;
    @Autowired
    CategoryService categoryService;

    @PostMapping
    public R<String> add(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());
        /*LambdaQueryWrapper<Category> lwq = new LambdaQueryWrapper<>();
        lwq.eq(Category::getId, dishDto.getCategoryId());*/
        dishService.saveWithFlavor(dishDto);

        return R.success("新增菜品成功");
    }

    /*
     *   分页查询菜品数据
     * */
    @GetMapping("/page")
    public R page(int page, int pageSize, String name) {
        Page<Dish> dishPage = new Page<>(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>();
        LambdaQueryWrapper<Dish> dishLwq = new LambdaQueryWrapper<>();
        dishLwq.like(name != null, Dish::getName, name);
        //排序
        dishLwq.orderByDesc(Dish::getUpdateTime);
        dishService.page(dishPage, dishLwq);
        BeanUtils.copyProperties(dishPage, dishDtoPage, "records");
        List<Dish> records = dishPage.getRecords();
        //创建dishDtos
        //ArrayList<DishDto> dishDtos = new ArrayList<>();
       /* for (Dish record : records) {
            //遍历获得菜品分类的id
            Long categoryId = record.getCategoryId();
            //通过id查询分类name
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                String categoryName = category.getName();
                //把name放入DishDto中
                DishDto dishDto = new DishDto();
                dishDto.setCategoryName(categoryName);
                BeanUtils.copyProperties(record, dishDto);
                dishDtos.add(dishDto);
            }
        }*/
        // 拉姆达表达式的写法： List<Dish> records ---> List<DishDto> dishDtos
        List<DishDto> dishDtos = records.stream().map((dish) -> {
            Long categoryId = dish.getCategoryId();
            Category category = categoryService.getById(categoryId);
            String categoryName = category.getName();
            DishDto dishDto = new DishDto();
            dishDto.setCategoryName(categoryName);
            BeanUtils.copyProperties(dish, dishDto);
            return dishDto;
        }).collect(Collectors.toList());
        dishDtoPage.setRecords(dishDtos);
        return R.success(dishDtoPage);
    }

    /*
     *   修改菜品数据    回显数据
     * */
    @GetMapping("/{id}")
    public R<DishDto> select(@PathVariable Long id) {
        //查询菜品数据
        Dish dish = dishService.getById(id);
        //查询对应菜品口味数据
        LambdaQueryWrapper<DishFlavor> dishFlavorLqw = new LambdaQueryWrapper<>();
        dishFlavorLqw.eq(DishFlavor::getDishId, id);
        //通过id查询口味数据集合
        List<DishFlavor> list = dishFlavorService.list(dishFlavorLqw);
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish, dishDto);
        dishDto.setFlavors(list);
        return R.success(dishDto);
    }

    /*
     *   修改菜品
     * */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        dishService.updateWithFlavor(dishDto);
        return R.success("需修改成功");
    }

    /*
     *   删除菜品  删除菜品关联的口味  还需判断是否关联套餐
     * */
    @DeleteMapping
    public R delete(@RequestParam List<Long> ids) {
        return dishService.delete(ids);
    }

    /*
     *   起售/停售 批量起售/批量停售
     * */
    @PostMapping("/status/{status}")
    public R<String> updateStatus(@PathVariable Integer status, @RequestParam List<Long> ids) {
        LambdaUpdateWrapper<Dish> dishLqw = new LambdaUpdateWrapper<>();
        dishLqw.in(Dish::getId, ids);
        dishLqw.set(Dish::getStatus, status);
        for (Long id : ids) {
            Dish dish = new Dish();
            dish.setId(id);
            dish.setStatus(status);
            boolean update = dishService.update(dishLqw);
            if (!update) {
                return R.error("操作失败，请勿重复操作");
            }
        }
        return R.success("操作成功");
    }

    /*
     *  根据分类id查询该分类下的所有菜品集合
     * */
/*    @GetMapping("/list")
    public R<List<Dish>> list(Dish dish) {
        //这里可以传categoryId
        //构造查询条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        //添加条件，查询状态为1（起售状态）的菜品
        queryWrapper.eq(Dish::getStatus, 1);
        //添加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(queryWrapper);
        return R.success(list);
    }*/

    /*
     *   根据分类id查询该分类下的所有菜品集合
     * */
    @GetMapping("/list")
    public R list(Long categoryId) {
        //获取菜品集合
        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
        qw.eq(categoryId != null, Dish::getCategoryId, categoryId);
        //添加条件，查询状态为1（起售状态）的菜品
        qw.eq(Dish::getStatus, 1);
        //添加排序条件
        qw.orderByDesc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        //获取菜品集合
        List<Dish> dishList = dishService.list(qw);
        //创建菜品口味关联对象集合
        ArrayList<DishDto> dishDtos = new ArrayList<>();
        //遍历菜品查询每个菜品口味
        for (Dish dish1 : dishList) {
            //先创建菜品口味关联对象
            DishDto dishDto = new DishDto();
            //把dish属性赋值dishDto
            BeanUtils.copyProperties(dish1, dishDto);
            //通过菜品口味表查询菜品的口味数据  select * from dish_flavours where dish_id = ?
            LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
            lqw.eq(DishFlavor::getDishId, dish1.getId());
            List<DishFlavor> dishFlavorList = dishFlavorService.list(lqw);
            //把查询到菜品对应口味集合赋值给dishDto
            dishDto.setFlavors(dishFlavorList);
            //把菜品口味关联对象添加入集合中
            dishDtos.add(dishDto);
        }
        return R.success(dishDtos);
    }
}
